package jast;
import java.io.IOException;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import tool.AutoCompile;

public class JAST {
	public static void main(String[] args) throws ParseException, IOException {
		// Create a Parser
		CommandLineParser parser = new DefaultParser();
		Options options = new Options();
		options.addOption("h", "help", false, "Print this usage information");
		options.addOption("c", "cfg", true, "Create the control flow graph");
		options.addOption("j", "jcompile", true, "Compile the java file");
		options.addOption("s", "stub", true, "Stub the program");
		options.addOption("p", "prime", true, "Print the basis path set");
//		options.addOption("e", "exec", true, "Execute the program");
		Option e = Option.builder("e")
                .required(false)
                .hasArgs()
                .argName("exec")
                .desc("Execute the program")
                .build();
		options.addOption(e);
		options.addOption("d", "dest", true, "Destination to save program output to");
		try{
			// Parse the program arguments
			CommandLine commandLine = parser.parse(options, args);
			// Set the appropriate variables based on supplied options
			String file = null;
			if (commandLine.hasOption('d')) {
				file = commandLine.getOptionValue('d');
			}
			if (commandLine.hasOption('h')) {
				// automatically generate the help statement
				HelpFormatter formatter = new HelpFormatter();
				formatter.printHelp("JAST", options);
			}
			if (commandLine.hasOption('c')) {
				(new CfgCreator()).createCfg(commandLine.getOptionValue("c"));
			}
			if (commandLine.hasOption('j')) {
				(new AutoCompile()).compile(commandLine.getOptionValue("j"));
			}
			if (commandLine.hasOption('p')) {
				(new PrimePathGen()).genPrimePath(commandLine.getOptionValue("p"));
			}
			if (commandLine.hasOption('e')) {
				System.out.println(commandLine.getOptionValues("e")[0]);
				System.out.println(commandLine.getOptionValues("e")[1]);
				(new ProgExec()).exec(commandLine.getOptionValues("e")[0], commandLine.getOptionValues("e")[1]);
			}
			if (commandLine.hasOption('s')) {
				if(file == null)
					(new ProgStub()).stub(commandLine.getOptionValue("s"));
				else
					(new ProgStub()).stub(commandLine.getOptionValue("s"),file);
			}
		}catch(ParseException exp) {
		    System.out.println("Unexpected exception:" + exp.getMessage());
		}
	}
}